//标识：区分当前是新增还是修改
let editId = ''

// 验证当前用户是否登录
ckeckLogin()
// 渲染页面数据
renderUserName()
// 退出登录
document.querySelector('#logout').addEventListener('click', function () {
    // 删除token
    localStorage.removeItem('token')
    location.href = './login.html'
})

// 更新用户名
function renderUserName() {
    const username = localStorage.getItem('username')
    document.querySelector('.username').innerHTML = username
}

// 点击跳出弹层
const modal = document.querySelector('#modal');
    // 通过模板实例化一个弹层
    const statusModal = new bootstrap.Modal(modal);
    // 展示弹层
document.querySelector('#openModal').addEventListener('click', function (e) {
    e.preventDefault()
    statusModal.show();
})

// 显示所有的信息
async function add() {
    const list = document.querySelector('.list')
    const res = await axios({ url: '/students' })
    list.innerHTML = res.data.map((item, index) => {
        return `<tr>
         <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.gender === 0 ? '男' : '女'}</td>
        <td>第${index + 1}组</td>
        <td>${item.hope_salary}</td>
        <td>${item.salary}</td>
        <td>${item.province}${item.city}${item.area}</td>
        <td>
          <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id =${item.id}></i></a>
          <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id =${item.id}></i></a>
         </td>
        </tr>`
    }).join('')
    document.querySelector('.total').innerText = res.data.length
}
add()


// 新增表格数据
const submit = document.querySelector('#submit')
submit.addEventListener('click', async function (e) {
    const addForm = document.querySelector('.g-3')
    const formData = serialize(addForm, { hash: true, empty: true })
    
    if(editId===''){
        await axios({
            url: '/students',
            method: 'POST',
            hesders: {
                Authorization: localStorage.getItem('token')
            },
            data: {
                name: formData.name,
                age: Number(formData.age),
                gender: Number(formData.gender),
                province: formData.province,
                city: formData.city,
                area: formData.area,
                hope_salary: Number(formData.hope_salary),
                salary: Number(formData.salary),
                group: Number(formData.group)
            }
        })
    }else{
        await axios({
            url: '/students'+editId,
            method: 'PUT',
            hesders: {
                Authorization: localStorage.getItem('token')
            },
            data: {
                name: formData.name,
                age: Number(formData.age),
                gender: Number(formData.gender),
                province: formData.province,
                city: formData.city,
                area: formData.area,
                hope_salary: Number(formData.hope_salary),
                salary: Number(formData.salary),
                group: Number(formData.group)
            }
        })
    }
    add()

    // 关闭弹层
    statusModal.hide();

})
const province = document.querySelector('.province')
const city = document.querySelector('.city')
const area = document.querySelector('.area')
// 省
axios({
    url: '/api/province'
}).then(res => {
    province.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
})
province.addEventListener('change', function () {
    // 市
    axios({
        url: '/api/city',
        params: {
            pname: this.value
        }
    }).then(res => {
        city.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
    })
})
city.addEventListener('change', function () {
    // 区
    axios({
        url: '/api/area',
        params: {
            pname: province.value,
            cname: this.value
        }
    }).then(res => {
        // console.log(res);
        area.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
    })
})

// 删除表格数据
document.querySelector('.list').addEventListener('click', function (e) {
    e.preventDefault
    if (e.target.className === 'bi bi-trash') {
        // console.dir(e.target)
        // 3.删除表格数据
        // console.log('删除');
        // 企业级需求：二次确认
        if (confirm('是否删除该数据')) {
            axios({
                url: `/students/${e.target.dataset.id}`,
                method: 'DELETE',
                hesders: {
                    Authorization: localStorage.getItem('token')
                },
            }).then(res => {
                add()
                showToast('删除成功')
            })
        }
    }
})

// 修改表格数据
document.querySelector('.list').addEventListener('click', async function (e) {
    if (e.target.className === 'bi bi-pen') {
        const province = document.querySelector('.province')
        const city = document.querySelector('.city')
        const area = document.querySelector('.area')
        const {data} = await axios({
            url: `/students/${e.target.dataset.id}`
        })
        // 省
       axios({
            url: '/api/province'
        }).then(res => {
            province.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
        })
        // 市
        province.addEventListener('change', function () {
            axios({
                url: '/api/city',
                params: {
                    pname: this.value
                }
            }).then(res => {
                city.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
            })
        })
        // 区
        city.addEventListener('change', function () {
            axios({
                url: '/api/area',
                params: {
                    pname: province.value,
                    cname: this.value
                }
            }).then(res => {
                // console.log(res);
                area.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
            })
        })


        // 回填数据
          document.querySelector('[name=name]').value =data .name
          document.querySelector('#cb01').checked = data.gender === 0
          document.querySelector('#cb02').checked = data.gender === 1
          document.querySelector('[name=age]').value = data.age
          document.querySelector('[name=group]').value = data.group
          document.querySelector('[name=hope_salary]').value = data.hope_salary
          document.querySelector('[name=salary]').value = data.salary
          
        // 回填省
        axios({
            url: '/api/province'
        }).then(res => {
            province.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
            province.value=  data.province
            // 回填市
            axios({
                url: '/api/city',
                params: {
                    pname: province.value
                }
            }).then(res => {
                city.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
                city.value=data.city
                // 回填区
                axios({
                    url: '/api/area',
                    params: {
                        pname: province.value,
                        cname: city.value
                    }
                }).then(res => {
                    area.innerHTML = res.list.map(item => `<option>${item}</option>`).join('')
                    area.value=data.area
                })
                
            })
        })

        openModal()



    }
})
